package com.gri.saas;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gri.entities.Project;
import com.gri.utils.GriUtils;

/**
 * Servlet implementation class Authenticate
 */
public class Authenticate extends HttpServlet {

	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Authenticate() {
        super();
        // TODO Auto-generated constructor stub
    }
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
	
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) {
		String email = request.getParameter("email");
		String pwd = request.getParameter("pwd");
		String backLink = request.getParameter("backLink");
		request.getSession().setAttribute("message", "");
		if(backLink != null && !backLink.isEmpty()){
			/*
			 * This portion will be executed when user clicks on back link from create project screen.
			 */
					
			Connection con = null;
			try{
				con = GriUtils.getConnection();
				String custId = (String)request.getSession().getAttribute("custId");
				if(null != custId){
					getProjectDetailsInRequestScope(request,con,Integer.parseInt(custId));
					GriUtils.forwardToPage(request, response, "main.jsp");
				} else {
					/*
					 * If user clicks on link after logout
					 */
					GriUtils.forwardToPage(request, response, "login.jsp");
				}
								
			}catch(Exception ex){
				System.out.println("Exception occured when back link clicked : " + ex);
			}finally{
				try{
					if(null != con){
						con.close();
					}
				}catch(Exception ex){
					System.out.println("Exception occured when back link clicked and closing the connection: " + ex);
				}
			}
		} else if(email == null || email.isEmpty()|| pwd == null || pwd.isEmpty()){
			request.getSession().setAttribute("message", "Email and password can not be empty");
			GriUtils.forwardToPage(request, response, "login.jsp");
		} else {
			Connection con =null;
			ResultSet rs = null;
			try{
				con = GriUtils.getConnection();
				PreparedStatement st = con.prepareStatement("Select * from tbl_customer where lower(email) = ? and (lower(status)='active' or lower(status) = 'processing')");
				st.setString(1, email.toLowerCase());
				rs = st.executeQuery();
				String dbPwd = "";
				Integer custId=null;
				String userName = "";
				if(rs!=null){
					while(rs.next()){
						dbPwd = rs.getString("password");
						custId = rs.getInt("cust_id");
						userName = rs.getString("cust_name");
						
						if(null != pwd && pwd.equals(dbPwd)){						
							request.getSession().setAttribute("isloggedIn", "true");		
							request.getSession().setAttribute("userName", userName);
							request.getSession().setAttribute("custId", custId.toString());
							/*
							 * Fetching the projects list in session
							 */
							getProjectDetailsInRequestScope(request,con,custId);
							GriUtils.forwardToPage(request, response, "main.jsp");
						} else {
							request.getSession().setAttribute("message", "Please enter correct password");
							GriUtils.forwardToPage(request, response, "login.jsp");
						}
						break;
					}
					if(custId==null){
						request.getSession().setAttribute("message", "Please enter correct email");
						GriUtils.forwardToPage(request, response, "login.jsp");
					}
					rs.close();
				} else {
					request.getSession().setAttribute("message", "Please enter correct email");
					GriUtils.forwardToPage(request, response, "login.jsp");
				}
				con.close();
			
			}catch(Exception ex){
				request.getSession().setAttribute("message", "Sorry, some error occurred in server");
				GriUtils.forwardToPage(request, response, "login.jsp");
			} finally{
				try{
					if(rs != null)
						rs.close();
					if(con!=null)
						con.close();				
				}catch(Exception ex){
					
				}
			}
		}
	}


	private void getProjectDetailsInRequestScope(HttpServletRequest request,
			Connection con, Integer custId) throws Exception {
		String sql = "Select * from tbl_project where cust_id = ?";
		PreparedStatement stmt = con.prepareStatement(sql);
		stmt.setInt(1, custId);
		ResultSet rs = stmt.executeQuery();
		List<Project> projectList = new ArrayList<Project>();
		if(rs!=null){
			while(rs.next()){				
				projectList.add(createProjectEntity(rs));
			}
			rs.close();
		}
		request.getSession().setAttribute("projectList",projectList);
	}


	private Project createProjectEntity(ResultSet rs) throws Exception {
		Project project = new Project();
		project.setCustId(rs.getInt("cust_id"));
		project.setProjectId(rs.getInt("project_id"));
		project.setProjectKeywords(rs.getString("project_keywords"));
		project.setProjectName(rs.getString("project_name"));
		project.setProjectUrl(rs.getString("project_url"));
		return project;
	}
}
